<template>
  <div class="main-layout">
    <!-- 顶部标签栏 -->
    <div class="tabs-bar">
      <div class="tab-item active">
        溯源详情
        <span class="tab-close">×</span>
      </div>
    </div>
    <!-- 内容区 -->
    <div class="content-area">
      <div class="details-container">
        <!-- 顶部商品信息(没有问题) -->
        <div class="header">
          <div class="header-img-wrap">
            <!-- 商品封面图片 -->
            <img v-if="data.cover" :src="data.cover" class="main-img" />
          </div>
          <div class="header-info">
            <div class="title">{{ data.goodsName }}</div>
            <div class="meta-row">
              <span>生产批次：{{ data.batch }}</span>
              <span>保质期：{{ data.shelf }} 天</span>
            </div>
            <div class="meta-row">
              <span>生产许可证号：{{ data.license }}</span>
              <span>生产企业：{{ data.enterprise }}</span>
            </div>
          </div>
          <div class="header-btns">
            <el-button>修改基本信息</el-button>
            <el-button>导出溯源码</el-button>
          </div>
        </div>
        <!-- 产品检验报告图片上传与展示 -->
        <div class="section">
          <div class="section-title">产品检验报告</div>
          <div class="img-list">
            <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
              list-type="picture-card" :file-list="reportImgs" :on-preview="handlePreview" :on-remove="handleRemove"
              :on-success="handleAvatarSuccess1" :limit="9" :on-exceed="handleExceed" multiple>
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </div>
          <!-- <div class="img-tip" v-if="Array.isArray(reportImgs) && reportImgs.length >= 9"
            style="color: #f56c6c; font-size: 12px;">
            最多上传9张图片
          </div> -->
        </div>
        <el-tabs v-model="activeTab" class="tabs">
          <el-tab-pane label="养殖信息" name="breed">
            <!-- 养殖信息内容 -->
            <div class="tab-section">
              <div class="tab-title">养殖信息 <el-button class="set-btn" @click="showBreedDialog = true">设置</el-button>
              </div>
              <div class="info-row">
                <span>品种：{{ breedInfo.variety }}</span>
                <span>来源：{{ breedInfo.source }}</span>
                <br>
                <span>饲养天数：{{ breedInfo.housingDays }} 天</span>
                <span>饲料品牌：{{ breedInfo.feedBrand }}</span>
                <br>
                <span>饲养负责人：{{ breedInfo.herdsperson }}</span>
                <span>出栏日期：{{ moment(breedInfo.harvestDate).format('YYYY年MM月DD日') }}</span>
              </div>
              <!-- 养殖信息设置弹窗、保健信息、动检证、企业信息等内容继续放这里... -->
              <!-- 保健信息 -->
              <div class="tab-section">
                <div class="tab-title">保健信息 <el-button class="set-btn" @click="addHealthRow">新增行</el-button></div>
                <el-table :data="healthList" border style="width: 100%; margin-top: 10px;">
                  <el-table-column prop="keepDays" label="饲养天数" width="120">
                    <template #default="scope">
                      <el-input v-if="editIndex === scope.$index" v-model="editRow.keepDays" size="small" />
                      <span v-else>{{ scope.row.keepDays }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="healthcareMethod" label="保健方式" width="120">
                    <template #default="scope">
                      <el-input v-if="editIndex === scope.$index" v-model="editRow.healthcareMethod" size="small" />
                      <span v-else>{{ scope.row.healthcareMethod }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="lnjectMethod" label="保健方法" width="120">
                    <template #default="scope">
                      <el-input v-if="editIndex === scope.$index" v-model="editRow.lnjectMethod" size="small" />
                      <span v-else>{{ scope.row.lnjectMethod }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="180">
                    <template #default="scope">
                      <template v-if="editIndex === scope.$index">
                        <el-link @click="saveEdit(scope.$index)">保存</el-link>
                        <el-link @click="cancelEdit" style="margin-left: 8px;">取消</el-link>
                      </template>
                      <template v-else>
                        <el-link @click="startEdit(scope.$index, scope.row)">修改</el-link>
                        <el-link @click="deleteHealth(scope.$index)" style="margin-left: 8px;">删除</el-link>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <!-- 动检证图片上传与展示 -->
              <div class="tab-section">
                <div class="tab-title">动检证</div>
                <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
                  list-type="picture-card" :file-list="animalImgs" :on-preview="handlePreview" :on-remove="handleRemove"
                  :on-success="handleAvatarSuccess2" :limit="9" :on-exceed="handleExceed" multiple>
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
              <!-- 企业信息 -->
              <div class="tab-section">
                <div class="tab-title">企业信息 <el-button class="set-btn" @click="showfirmDialog = true">设置</el-button>
                </div>
                <div class="info-row">
                  <span>养殖场：{{ firmInfo.livestock }}</span>
                  <span>负责人：{{ firmInfo.responsibleName }}</span>
                  <span>存栏规模：{{ firmInfo.herd }}</span>
                </div>
                <el-dialog v-model="showfirmDialog" title="养殖企业信息" width="500px">
                  <el-form :model="firmForm" :rules="firmRules" ref="firmFormRef" label-width="100px"
                    style="padding: 24px 0;">
                    <el-form-item label="养殖场" prop="livestock" required>
                      <el-input v-model="firmForm.livestock" maxlength="30" show-word-limit placeholder="请输入品种" />
                    </el-form-item>
                    <el-form-item label="负责人" prop="responsibleName" required>
                      <el-input v-model="firmForm.responsibleName" maxlength="30" show-word-limit placeholder="请输入来源" />
                    </el-form-item>
                    <el-form-item label="存栏量（只）" prop="herd" required>
                      <el-input v-model="firmForm.herd" maxlength="5" show-word-limit placeholder="请输入饲养天数" />
                    </el-form-item>
                  </el-form>
                  <template #footer>
                    <el-button @click="showfirmDialog = false">取消</el-button>
                    <el-button type="primary" @click="handleFirmSave">保存</el-button>
                  </template>
                </el-dialog>
                <div class="tab-title" style="margin-top: 20px;">企业照片</div>
                <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
                  list-type="picture-card" :file-list="companyImgs" :on-preview="handlePreview"
                  :on-remove="handleRemove" :on-success="handleAvatarSuccess3" :limit="9" :on-exceed="handleExceed"
                  multiple>
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="屠宰信息" name="health">
            <!-- 屠宰信息内容 -->
            <div class="tab-section">
              <div class="tab-title">屠宰信息 <el-button class="set-btn" @click="showSlaughterDialog = true">设置</el-button>
              </div>
              <div class="info-row">
                <span>批次：{{ slaughterInfo.batch || '-' }}</span>
                <span>到厂均重：{{ slaughterInfo.actualWeighing || '-' }} 公斤</span>
              </div>
              <div class="info-row">
                <span>到厂时间：{{ moment(slaughterInfo.arrivalTime).format('YYYY年MM月DD日') }}</span>
                <span>屠宰时间：{{ moment(slaughterInfo.slaughterTime).format('YYYY年MM月DD日 ') }}</span>
              </div>
            </div>
            <el-dialog v-model="showSlaughterDialog" title="屠宰信息" width="500px">
              <el-form :model="slaughterForm" :rules="slaughterRules" ref="slaughterFormRef" label-width="120px"
                style="padding: 24px 0;">
                <el-form-item label="批次" prop="batch" required>
                  <el-input v-model="slaughterForm.batch" maxlength="30" show-word-limit placeholder="请输入批次" disabled />
                </el-form-item>
                <el-form-item label="到厂均重（公斤）" prop="actualWeighing" required>
                  <el-input v-model="slaughterForm.actualWeighing" maxlength="10" show-word-limit
                    placeholder="请输入到厂均重" />
                </el-form-item>
                <el-form-item label="到厂时间" prop="arrivalTime" required>
                  <el-date-picker v-model="slaughterForm.arrivalTime" type="datetime" value-format="YYYY-MM-DD"
                    placeholder="请选择到厂时间" style="width: 100%;" />
                </el-form-item>
                <el-form-item label="屠宰时间" prop="slaughterTime" required>
                  <el-date-picker v-model="slaughterForm.slaughterTime" type="datetime" value-format="YYYY-MM-DD"
                    placeholder="请选择屠宰时间" style="width: 100%;" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="showSlaughterDialog = false">取消</el-button>
                <el-button type="primary" @click="handleSlaughterSave">保存</el-button>
              </template>
            </el-dialog>
            <div class="tab-section">
              <div class="tab-title" style="color:#1890ff;font-weight:bold;">相关资质</div>
              <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
                list-type="picture-card" :file-list="slaughterImgs" :on-preview="handlePreview"
                :on-remove="handleRemove" :on-success="handleAvatarSuccess4" :limit="9" :on-exceed="handleExceed"
                multiple>
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
            <!-- 新增企业信息 -->
            <div class="tab-section">
              <div class="tab-title">企业信息 <el-button class="set-btn" @click="showCompanyDialog = true">设置</el-button>
              </div>
              <div class="info-row">
                <span>公司名称：{{ companyInfo.companyName }}</span>
                <span>成立时间：{{ moment(companyInfo.establishTime).format('YYYY年MM月DD日') }}</span>
                <span>公司地址：{{ companyInfo.provinceName }}{{ companyInfo.cityName || '' }}{{ companyInfo.countyName || ''
                  }}</span>
                <span>公司简介：{{ companyInfo.companyProfile }}</span>
              </div>
            </div>
            <el-dialog v-model="showCompanyDialog" title="屠宰企业信息" width="500px">
              <el-form :model="companyForm" :rules="companyRules" ref="CompanyFormRef" label-width="120px"
                style="padding: 24px 0;">
                <el-form-item label="公司名称" prop="companyName" required>
                  <el-input v-model="companyForm.companyName" maxlength="30" show-word-limit placeholder="请输入公司名称" />
                </el-form-item>
                <el-form-item label="公司地址" required>
                  <el-select placeholder="请选择省份" @change="handleProvinceChange" v-model="companyForm.provinceName"
                    style="width: 150px;margin-right: 20px;">
                    <el-option v-for="a in provinceList" :key="a.value" :label="a.label" :value="a.label"></el-option>
                  </el-select>
                  <el-select placeholder="请选择市" @change="handleCityChange" v-model="companyForm.cityName"
                    style="width: 150px;margin-right: 20px;">
                    <el-option v-for="a in cityList" :key="a.value" :label="a.label" :value="a.label"></el-option>
                  </el-select>
                  <el-select placeholder="请选择县" v-model="companyForm.countyName"
                    style="width: 150px;margin-right: 20px;">
                    <el-option v-for="a in districtList" :key="a.value" :label="a.label" :value="a.label"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="成立时间" prop="establishTime" required>
                  <el-date-picker v-model="companyForm.establishTime" type="datetime" value-format="YYYY-MM-DD"
                    placeholder="请选择成立时间" style="width: 100%;" />
                </el-form-item>
                <el-form-item label="公司简介" prop="companyProfile" required>
                  <el-input v-model="companyForm.companyProfile" maxlength="500" show-word-limit
                    placeholder="请输入公司简介" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="showSlaughterDialog = false">取消</el-button>
                <el-button type="primary" @click="handleCompanySave">保存</el-button>
              </template>
            </el-dialog>
            <!-- 新增企业照片 -->
            <div class="tab-section">
              <div class="tab-title" style="color:#1890ff;font-weight:bold;">企业照片</div>
              <div class="img-list">
                <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
                  list-type="picture-card" :file-list="companyImgs" :on-preview="handlePreview"
                  :on-remove="handleRemove" :on-success="handleAvatarSuccess5" :limit="9" :on-exceed="handleExceed"
                  multiple>
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="深加工信息" name="deepProcessing">
            <!-- 深加工信息内容 -->
            <div class="tab-section">
              <div class="tab-title">
                深加工信息
                <el-button class="set-btn" @click="showDeepDialog = true">设置</el-button>
              </div>
              <div class="info-row">
                <span>班组：{{ deepInfo.workTeam }}</span>
                <span>负责人：{{ deepInfo.manager }}</span>
              </div>
            </div>
            <el-dialog v-model="showDeepDialog" title="企业信息" width="500px">
              <el-form :model="deepForm" :rules="deepRules" ref="deepFormRef" label-width="100px"
                style="padding: 24px 0;">
                <el-form-item label="班组" prop="workTeam" required>
                  <el-input v-model="deepForm.workTeam" maxlength="30" show-word-limit placeholder="请输入班组" />
                </el-form-item>
                <el-form-item label="负责人" prop="manager" required>
                  <el-input v-model="deepForm.manager" maxlength="30" show-word-limit placeholder="请输入负责人" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="showDeepDialog = false">取消</el-button>
                <el-button type="primary" @click="handleDeepSave">保存</el-button>
              </template>
            </el-dialog>
            <!-- 食品安全信息 -->
            <div class="tab-section">
              <div class="tab-title" style="color:#1890ff;font-weight:bold;">食品安全信息</div>
              <div class="img-list">
                <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
                  list-type="picture-card" :file-list="foodSafeImgs" :on-preview="handlePreview"
                  :on-remove="handleRemove" :on-success="handleAvatarSuccess6" :limit="9" :on-exceed="handleExceed"
                  multiple>
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
            </div>
            <!-- 供应商信息（原料、辅料、添加剂、包材） -->
            <div class="tab-section">
              <div class="tab-title">
                <h3>供应商</h3>
              </div>
              <!-- 供应商信息分区（原料、辅料、添加剂、包材） -->
              <div class="block-card">
                <div class="block-title">
                  <span class="bar"></span><b>原料</b>
                </div>
                <div class="info-row">生产批次：{{ data.batch }}</div>

                <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
                  list-type="picture-card" :file-list="SupplierImgs1" :on-preview="handlePreview"
                  :on-remove="handleRemove" :on-success="handleAvatarSuccess7" :limit="9" :on-exceed="handleExceed"
                  multiple>
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
                <el-upload class="upload-card" action="#" :show-file-list="false">
                  <div class="upload-inner">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </div>
                </el-upload>
              </div>

              <hr>
              <div class="block-card">
                <div class="block-title">
                  <span class="bar"></span><b>辅料</b>
                </div>
                <div class="info-row">生产批次：{{ data.batch }}</div>
                <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
                  list-type="picture-card" :file-list="SupplierImgs2" :on-preview="handlePreview"
                  :on-remove="handleRemove" :on-success="handleAvatarSuccess8" :limit="9" :on-exceed="handleExceed"
                  multiple>
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
              <el-upload class="upload-card" action="#" :show-file-list="false">
                <div class="upload-inner">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
              <hr>
              <div class="block-card">
                <div class="block-title">
                  <span class="bar"></span><b>添加剂</b>
                </div>
                <div class="info-row">生产批次：{{ data.batch }}</div>

                <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
                  list-type="picture-card" :file-list="SupplierImgs3" :on-preview="handlePreview"
                  :on-remove="handleRemove" :on-success="handleAvatarSuccess9" :limit="9" :on-exceed="handleExceed"
                  multiple>
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
              <el-upload class="upload-card" action="#" :show-file-list="false">
                <div class="upload-inner">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
              <hr>
              <div class="block-card">
                <div class="block-title">
                  <span class="bar"></span><b>包料</b>
                </div>
                <div class="info-row">生产批次：{{ data.batch }}</div>

                <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
                  list-type="picture-card" :file-list="SupplierImgs4" :on-preview="handlePreview"
                  :on-remove="handleRemove" :on-success="handleAvatarSuccess10" :limit="9" :on-exceed="handleExceed"
                  multiple>
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
              <el-upload class="upload-card" action="#" :show-file-list="false">
                <div class="upload-inner">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>

            <!-- 企业信息 -->
            <div class="tab-section">
              <div class="tab-title">企业信息 <el-button class="set-btn" @click="showEnterpriseDialog = true">设置</el-button>
              </div>
              <div class="info-row">
                <span>公司名称：{{ enterpriseInfo.enterpriseName }}</span>
                <span>生产许可证号：{{ enterpriseInfo.license }}</span>
              </div>
            </div>
            <el-dialog v-model="showEnterpriseDialog" title="企业信息" width="500px">
              <el-form :model="enterpriseForm" :rules="enterpriseRules" ref="eterpriseFormRef" label-width="100px"
                style="padding: 24px 0;">
                <el-form-item label="公司名称" prop="enterpriseName" required>
                  <el-input v-model="enterpriseForm.enterpriseName" maxlength="30" show-word-limit
                    placeholder="请输入公司名称" />
                </el-form-item>
                <el-form-item label="生产许可证号" prop="license" required>
                  <el-input v-model="enterpriseForm.license" maxlength="30" show-word-limit placeholder="请输入生产许可证号" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="showEnterpriseDialog = false">取消</el-button>
                <el-button type="primary" @click="handleEnterpriseSave">保存</el-button>
              </template>
            </el-dialog>
            <!-- 企业照片 -->
            <el-upload class="upload-demo" action="Http://localhost:5153/api/Traceability/UploadFile"
              list-type="picture-card" :file-list="SupplierImgs4" :on-preview="handlePreview" :on-remove="handleRemove"
              :on-success="handleAvatarSuccess11" :limit="9" :on-exceed="handleExceed" multiple>
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- tabs区块，所有tab内容都放在同一个el-tabs里 -->

    </div>
  </div>
</template>

<script setup lang="ts">
// 引入vue、element-plus、路由、moment等依赖
import { ref, onMounted, reactive, watch } from 'vue';
import { Plus, Close } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, type UploadProps } from 'element-plus';
import { useRoute } from 'vue-router';
import moment from 'moment';
import axios from 'axios';

const imageUrl = ref('')

const handleAvatarSuccess = (img: any) => {
  //那个字段是绑定的这个  什么？这不是添加 添加在最下面呢
  add.img = 'http://' + img
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 路由参数
const route = useRoute();
// 当前激活Tab
const activeTab = ref('breed');

// 商品详情数据==============================================================================================================================================================
const data: any = ref<any>({});
// 页面加载时，解析路由参数获取详情数据
onMounted(() => {
  const batch = localStorage.getItem('batch');
  const goodsName = localStorage.getItem('goodsName');
  const shelf = localStorage.getItem('shelf');
  const license = localStorage.getItem('license');
  const enterprise = localStorage.getItem('enterprise');
  const cover = localStorage.getItem('cover');
  if (batch) {
    // 反填养殖信息
    getDataBreed(batch);
    //显示保健信息
    getDataHealth(batch);
    //反填企业信息
    getDataFirm(batch);
    //反填屠宰企业信息
    getDataCompany(batch);
    //反填深加工信息
    getDataDeep(batch);
    getDataEnterprise(batch);
    // 赋值到表单
    breedForm.batch = batch;
    breedInfo.value.batch = batch;
    healthList.value.batch = batch;
    editRow.value.batch = batch;
    firmForm.batch = batch;
    firmInfo.value.batch = batch;
    companyForm.batch = batch;
    deepForm.batch = batch;
    deepInfo.batch = batch;
    enterpriseForm.batch = batch;
    enterpriseInfo.value.batch = batch;
    add.batch = batch;
    data.value.batch = batch;
    data.value.goodsName = goodsName;
    data.value.shelf = shelf;
    data.value.license = license;
    data.value.enterprise = enterprise;
    data.value.cover = cover;
  }
});

// 产品检验报告图片相关========================================================================================================================================================

// function beforeReportUpload(file: File) {
//   // 校验图片类型和数量
//   const isImage = file.type.startsWith('image/');
//   if (!isImage) {
//     ElMessage.error('只能上传图片文件');
//     return false;
//   }
//   if (reportImgs.value.length >= 9) {
//     ElMessage.error('最多上传9张图片');
//     return false;
//   }
//   return true;
// }
// function handleReportImgChange(file: any) {
//   // 读取图片为base64并添加到数组
//   const reader = new FileReader();
//   reader.onload = (e) => {
//     reportImgs.value.push(e.target?.result as string);
//   };
//   reader.readAsDataURL(file.raw);
// }
// function removeReportImg(idx: number) {
//   reportImgs.value.splice(idx, 1);
// }

// 养殖信息弹窗表单及校验==========================================================================================================================================
const breedFormRef = ref();
const breedForm: any = reactive({
  "variety": "",
  "source": "",
  "housingDays": 0,
  "feedBrand": "",
  "herdsperson": "",
  "harvestDate": "2025-07-09",
  "batch": ''
});
const breedRules = {
  variety: [
    { required: true, message: '请输入品种', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/, message: '仅限中文、字母、数字，最多30位', trigger: 'blur' }
  ],
  source: [
    { required: true, message: '请输入来源', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/, message: '仅限中文、字母、数字，最多30位', trigger: 'blur' }
  ],
  housingDays: [
    { required: true, message: '请输入饲养天数', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '仅限数字，最多5位', trigger: 'blur' }
  ],
  feedBrand: [
    { required: true, message: '请输入饲料品牌', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/, message: '仅限中文、字母、数字，最多30位', trigger: 'blur' }
  ],
  herdsperson: [
    { required: true, message: '请输入饲养负责人', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/, message: '仅限中文、字母、数字，最多30位', trigger: 'blur' }
  ],
  harvestDate: [
    { required: true, message: '请选择出栏日期', trigger: 'change' }
  ]
};
// 展示用的养殖信息对象
const breedInfo: any = ref({
  "breedId": 0,
  "variety": "",
  "source": "",
  "housingDays": 0,
  "feedBrand": "",
  "herdsperson": "",
  "harvestDate": "2025-07-09",
  "batch": ""
});
const showBreedDialog = ref(false);//handleBreedSave
const handleBreedSave = () => {
  // 如果有生产批次且有主键id，则为修改，否则为新增
  if (breedInfo.value.batch && breedInfo.value.breedId) {
    axios.post("http://localhost:5153/api/Breed/UpdateBreed", breedForm).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        showBreedDialog.value = false;
        Object.assign(breedInfo.value, breedForm);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  } else if (breedInfo.value.batch) {
    axios.post("http://localhost:5153/api/Breed/AddBreed", breedForm).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        showBreedDialog.value = false;
        Object.assign(breedInfo.value, breedForm);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  } else {
    ElMessage.error('生产批次不能为空');
  }
}
//养殖信息反填
const getDataBreed = (batch: any) => {
  axios.get("http://localhost:5153/api/Breed/GetBreed", { params: { Batch: batch } }).then(res => {
    if (res.data && res.data.data) {
      breedInfo.value = res.data.data;
    }
  });
}
// 监听设置弹窗打开，反填数据
watch(showBreedDialog, (val) => {
  if (val && breedInfo.value && breedInfo.value.variety) {
    // 只要主页面有值就反填
    Object.assign(breedForm, breedInfo.value);
  }
});

// 保健信息表格相关======================================================================================================================================================================================
const healthList: any = ref([]);
const getDataHealth = (batch: any) => {
  axios.get("http://localhost:5153/api/Breed/GetHealthcare", { params: { Batch: batch } }).then(res => {
    if (res.data && res.data.data) {
      healthList.value = res.data.data
    }
  })
}

// 页面加载时
onMounted(() => {
  const batch = localStorage.getItem('batch');
  if (batch) {
    getDataHealth(batch);
  }
});

const editIndex = ref(-1);
const editRow = ref({
  "healthcareId": 0,
  "keepDays": 0,
  "healthcareMethod": "",
  "lnjectMethod": "",
  "batch": ''
});
function addHealthRow() {
  if (editIndex.value !== -1) return;
  healthList.value.push({ keepDays: 0, healthcareMethod: '', lnjectMethod: '', batch: editRow.value.batch });
  startEdit(healthList.value.length - 1, { keepDays: 0, healthcareMethod: '', lnjectMethod: '', batch: editRow.value.batch });
}
function startEdit(idx: any, row: any) {
  editIndex.value = idx;
  editRow.value = { ...row };
}
//添加修改
function saveEdit(idx: any) {
  if (editRow.value.healthcareId) {
    // 修改
    axios.post("http://localhost:5153/api/Breed/UpdateHealthcare", editRow.value).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        getDataHealth(editRow.value.batch);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  } else {
    // 新增
    axios.post("http://localhost:5153/api/Breed/AddHealthcare", editRow.value).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        getDataHealth(editRow.value.batch);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  }
  healthList.value[idx] = { ...editRow.value };
  editIndex.value = -1;
}
function cancelEdit() {
  if (
    healthList.value[editIndex.value] &&
    !healthList.value[editIndex.value].keepDays &&
    !healthList.value[editIndex.value].healthcareMethod &&
    !healthList.value[editIndex.value].lnjectMethod
  ) {
    healthList.value.splice(editIndex.value, 1);
  }
  editIndex.value = -1;
}
//删除方法
function deleteHealth(idx: any) {
  const row = healthList.value[idx];
  ElMessageBox.confirm(
    '确定要删除该保健信息吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    if (row && row.healthcareId) {
      axios.get(`http://localhost:5153/api/Breed/DelHealthcare`, { params: { HealthcareId: row.healthcareId } }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          getDataHealth(row.batch);
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    }
    healthList.value.splice(idx, 1);
    if (editIndex.value === idx) editIndex.value = -1;
  }).catch(() => {
    // 用户取消，无操作
  });
}

// 养殖企业信息相关======================================================================================================================================================================================
const showfirmDialog = ref(false);
const firmFormRef = ref();
const firmForm = reactive({
  "firmId": 0,
  "livestock": "",
  "responsibleName": "",
  "herd": '',
  "batch": ""
})
const firmInfo = ref({
  "firmId": 0,
  "livestock": "",
  "responsibleName": "",
  "herd": '',
  "batch": ""
})
const firmRules = {
  livestock: [
    { required: true, message: '请输入养殖场', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/, message: '仅限中文、字母、数字，最多30位', trigger: 'blur' }
  ],
  responsibleName: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/, message: '仅限中文、字母、数字，最多30位', trigger: 'blur' }
  ],
  herd: [
    { required: true, message: '请输入存栏量（只）', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '仅限数字，最多5位', trigger: 'blur' }
  ]
};
const handleFirmSave = () => {
  if (!firmForm.batch) {
    ElMessage.error('生产批次不能为空');
    return;
  }
  // 有 firmId 且有 batch，走修改
  if (firmForm.firmId && firmForm.batch) {
    axios.post("http://localhost:5153/api/Breed/UpdateFirm", firmForm).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        showfirmDialog.value = false;
        Object.assign(firmInfo.value, firmForm);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  } else if (firmForm.batch) {
    // 没有 firmId 但有 batch，走新增
    axios.post("http://localhost:5153/api/Breed/AddFirm", firmForm).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        showfirmDialog.value = false;
        Object.assign(firmInfo.value, firmForm);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  }
}
const getDataFirm = (batch: any) => {
  axios.get("http://localhost:5153/api/Breed/GetFirm", { params: { Batch: batch } }).then(res => {
    firmInfo.value = res.data.data
  })
}

// 监听企业信息弹窗打开，反填数据
watch(showfirmDialog, (val) => {
  if (val) {
    Object.assign(firmForm, (firmInfo.value || firmInfo || { livestock: '', responsibleName: '', herd: '', batch: '' }));
  }
});

// 屠宰信息相关==========================================================================================================================================
const showSlaughterDialog = ref(false);
const slaughterFormRef = ref();
const slaughterForm = reactive({
  'slaughterId': 0, // 假如有主键
  'batch': '',
  'actualWeighing': '',
  'arrivalTime': '',
  'slaughterTime': ''
});
const slaughterInfo = ref({
  'slaughterId': 0,
  'batch': '',
  'actualWeighing': '',
  'arrivalTime': '',
  'slaughterTime': ''
});
const slaughterRules = {
  batch: [{ required: true, message: '请输入批次', trigger: 'blur' }],
  actualWeighing: [{ required: true, message: '请输入到厂均重', trigger: 'blur' }],
  arrivalTime: [{ required: true, message: '请选择到厂时间', trigger: 'change' }],
  slaughterTime: [{ required: true, message: '请选择屠宰时间', trigger: 'change' }]
};
const handleSlaughterSave = () => {
  if (!slaughterForm.batch) {
    ElMessage.error('批次不能为空');
    return;
  }
  // 有主键，走修改
  if (slaughterForm.slaughterId != 0 && slaughterForm.batch) {
    axios.post("http://localhost:5153/api/Slaughter/UpdateSlaughter", slaughterForm).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        showSlaughterDialog.value = false;
        Object.assign(slaughterInfo.value, slaughterForm);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  } else if (slaughterForm.batch) {
    // 新增
    axios.post("http://localhost:5153/api/Slaughter/AddSlaughter", slaughterForm).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        showSlaughterDialog.value = false;
        Object.assign(slaughterInfo.value, slaughterForm);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  }
};
const getDataSlaughter = (batch: string) => {
  axios.get("http://localhost:5153/api/Slaughter/GetSlaughter", { params: { Batch: batch } }).then(res => {
    if (res.data && res.data.data) {
      slaughterInfo.value = res.data.data;
    }
  });
};

onMounted(() => {
  const batch = localStorage.getItem('batch');
  if (batch) getDataSlaughter(batch);
});

watch(showSlaughterDialog, (val) => {
  if (val) {
    // 反填
    Object.assign(slaughterForm, slaughterInfo.value || { batch: localStorage.getItem('batch') || '', actualWeighing: '', arrivalTime: '', slaughterTime: '' });
    // 默认批次
    if (!slaughterForm.batch) slaughterForm.batch = localStorage.getItem('batch') || '';
  }
});

//屠宰企业相关资料====================================================================================================================================================
const showCompanyDialog = ref(false);
const companyFormRef = ref();
const companyForm = reactive({
  "companyId": 0,
  "companyName": "",
  "provinceName": "",
  "cityName": "",
  "countyName": "",
  "establishTime": "2025-07-11T06:58:09.477Z",
  "companyProfile": "",
  "batch": ""
});
const companyInfo = ref({
  "companyId": 0,
  "companyName": "",
  "provinceName": "",
  "cityName": "",
  "countyName": "",
  "establishTime": "2025-07-11T06:58:09.477Z",
  "companyProfile": "",
  "batch": ""
});
const companyRules = {
  companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  provinceName: [{ required: true, message: '请选择省份', trigger: 'blur' }],
  cityName: [{ required: true, message: '请选择市', trigger: 'change' }],
  countyName: [{ required: true, message: '请选择县', trigger: 'change' }],
  establishTime: [{ required: true, message: '请选择成立时间', trigger: 'change' }],
  companyProfile: [{ required: true, message: '请输入公司简介', trigger: 'change' }],
};

// 查询屠宰企业信息
const getDataCompany = (batch: string) => {
  axios.get("http://localhost:5153/api/Slaughter/GetCompany", { params: { Batch: batch } }).then(res => {
    if (res.data && res.data.data) {
      companyInfo.value = res.data.data;
    } else {
      companyInfo.value = {
        companyId: 0,
        companyName: '',
        provinceName: '',
        cityName: '',
        countyName: '',
        establishTime: '',
        companyProfile: '',
        batch: batch
      };
    }
  });
};
// 弹窗打开时反填
watch(showCompanyDialog, (val) => {
  if (val) {
    Object.assign(companyForm, companyInfo.value || { companyId: 0, companyName: '', provinceName: '', cityName: '', countyName: '', establishTime: '', companyProfile: '', batch: localStorage.getItem('batch') || '' });
    if (!companyForm.batch) companyForm.batch = localStorage.getItem('batch') || '';
  }
});

// 保存屠宰企业信息
const handleCompanySave = () => {
  if (!companyForm.batch) {
    ElMessage.error('批次不能为空');
    return;
  }
  // companyId为0且有批次，走新增
  if (companyForm.companyId === 0 && companyForm.batch) {
    axios.post("http://localhost:5153/api/Slaughter/AddCompany", companyForm).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        showCompanyDialog.value = false;
        Object.assign(companyInfo.value, companyForm);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  } else if (companyForm.batch) {
    // 有主键，走修改
    axios.post("http://localhost:5153/api/Slaughter/UpdateCompany", companyForm).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        showCompanyDialog.value = false;
        Object.assign(companyInfo.value, companyForm);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  }
};
//省市县全国
import { regionData } from 'element-china-area-data'
import type { UploadUserFile } from 'element-plus/lib';
//省
const provinceList = regionData
//市
const cityList = ref<any[]>([])
//县
const districtList = ref<any[]>([])
//省份改变时 ，加载对应城市
const handleProvinceChange = (provinceCode: any) => {
  companyForm.cityName = ''
  companyForm.countyName = ''
  const province = regionData.find(item => item.label === provinceCode)
  if (province && province.children) {
    cityList.value = province.children
  }
}
//是份改变时 ，加载对应城市
const handleCityChange = (cityCode: any) => {
  companyForm.countyName = ''
  const province = regionData.find(item => item.label === companyForm.provinceName)
  if (province) {
    const city = province.children?.find(item => item.label === cityCode)
    if (city?.children) {
      districtList.value = city.children
    }
    else {
      districtList.value = []
      console.warn('当前城市无区县数据')
    }
  }
}
//监听省变化
watch(() => companyForm.provinceName, (newVal) => {
  if (newVal) {
    handleProvinceChange(newVal)
  }
})
//监听省变化
watch(() => companyForm.cityName, (newVal) => {
  if (newVal) {
    handleCityChange(newVal)
  }
})

// 深加工信息弹窗相关=================================================================================================================
const showDeepDialog = ref(false);
const deepFormRef = ref();
const deepForm = reactive({
  "deepProcessingId": 0,
  "workTeam": "",
  "manager": "",
  "batch": ""
});
const deepRules = {
  workTeam: [
    { required: true, message: '请输入班组', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/, message: '仅限中文、字母、数字，最多30位', trigger: 'blur' }
  ],
  manager: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/, message: '仅限中文、字母、数字，最多30位', trigger: 'blur' }
  ]
};

// 展示用的深加工信息对象
const deepInfo: any = ref({
  "deepProcessingId": 0,
  "workTeam": "",
  "manager": "",
  "batch": ""
});

const handleDeepSave = () => {
  deepFormRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    if (!deepForm.batch) {
      ElMessage.error('生产批次不能为空');
      return;
    }
    if (deepForm.deepProcessingId === 0 && deepForm.batch) {
      // 新增
      axios.post("http://localhost:5153/api/DeepProcessing/AddDeepProcessing", deepForm).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          showDeepDialog.value = false;
          getDataDeep(deepForm.batch); // 刷新主页面显示
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else if (deepForm.batch) {
      // 修改
      axios.post("http://localhost:5153/api/DeepProcessing/UpdateDeepProcessing", deepForm).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          showDeepDialog.value = false;
          getDataDeep(deepForm.batch); // 刷新主页面显示
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    }
  });
};

// 监听深加工信息弹窗打开，反填数据
watch(showDeepDialog, (val) => {
  if (val) {
    Object.assign(
      deepForm,
      deepInfo.value ||
      { deepProcessingId: 0, workTeam: '', manager: '', batch: localStorage.getItem('batch') || '' }
    );
    if (!deepForm.batch) deepForm.batch = localStorage.getItem('batch') || '';
  }
});

// 获取深加工信息列表
const getDataDeep = (batch: any) => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetDeepProcessing", { params: { Batch: batch } }).then(res => {

    deepInfo.value = res.data.data;
  });
};


// 深加工企业信息=================================================================================================================
const showEnterpriseDialog = ref(false);
const enterpriseFormRef = ref();
const enterpriseForm = reactive({
  enterpriseId: 0,
  enterpriseName: '',
  license: '',
  batch: ''
});
const enterpriseInfo = ref({
  enterpriseId: 0,
  enterpriseName: '',
  license: '',
  batch: ''
});
const enterpriseRules = {
  enterpriseName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/, message: '仅限中文、字母、数字，最多30位', trigger: 'blur' }
  ],
  license: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/, message: '仅限中文、字母、数字，最多30位', trigger: 'blur' }
  ]
};
// 获取深加工企业信息
const getDataEnterprise = (batch: any) => {
  axios.get('http://localhost:5153/api/DeepProcessing/GetEnterprise', { params: { Batch: batch } }).then(res => {
    if (res.data && res.data.data) {
      enterpriseInfo.value = res.data.data;
    } else {
      enterpriseInfo.value = { enterpriseId: 0, enterpriseName: '', license: '', batch: enterpriseInfo.value.batch };
    }
  });
};
// 监听弹窗打开反填
watch(showEnterpriseDialog, (val) => {
  if (val) {
    Object.assign(enterpriseForm, enterpriseInfo.value || { enterpriseId: 0, enterpriseName: '', license: '', batch: localStorage.getItem('batch') || '' });
    if (!enterpriseForm.batch) enterpriseForm.batch = localStorage.getItem('batch') || '';
  }
});
// 保存深加工企业信息
const handleEnterpriseSave = () => {
  if (enterpriseForm.enterpriseId == 0 && enterpriseForm.batch) {
    // 新增
    axios.post('http://localhost:5153/api/DeepProcessing/AddEnterprise', enterpriseForm).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        showEnterpriseDialog.value = false;
        getDataEnterprise(enterpriseForm.batch);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  } else if (enterpriseForm.batch) {
    // 修改
    axios.post('http://localhost:5153/api/DeepProcessing/UpdateEnterprise', enterpriseForm).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        showEnterpriseDialog.value = false;
        getDataEnterprise(enterpriseForm.batch);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  }
};
// 供应商相关图片=================================================================================================================
const reportImgs = ref<UploadUserFile[]>([]);//产品检验报告
const animalImgs = ref<UploadUserFile[]>([]);//动检证
const companyImgs = ref<UploadUserFile[]>([]);//养殖企业图片
const slaughterImgs = ref<UploadUserFile[]>([]);//屠宰相关资源
const slaughterFirmImgs = ref<UploadUserFile[]>([]);//屠宰企业图片
const foodSafeImgs = ref<UploadUserFile[]>([]);//食品安全信息
const DeepEnterpriseImgs = ref<UploadUserFile[]>([]);//深加工企业图片
const SupplierImgs1 = ref<UploadUserFile[]>([]);//深加工原料图片
const SupplierImgs2 = ref<UploadUserFile[]>([]);//深加工辅料图片
const SupplierImgs3 = ref<UploadUserFile[]>([]);//深加工添加剂图片
const SupplierImgs4 = ref<UploadUserFile[]>([]);//深加工包材图片

const add = reactive({
  "supplierType": 0,
  "batch": "",
  "img": ""
})
//添加
const handleAvatarSuccess1: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 1
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg1();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}
const handleAvatarSuccess2: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 2
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg2();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}
const handleAvatarSuccess3: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 3
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg3();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}
const handleAvatarSuccess4: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 4
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg4();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}
const handleAvatarSuccess5: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 5
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg5();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}
const handleAvatarSuccess6: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 6
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg6();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}
const handleAvatarSuccess7: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 7
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg7();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}
const handleAvatarSuccess8: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 8
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg8();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}
const handleAvatarSuccess9: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 9
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg9();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}
const handleAvatarSuccess10: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 10
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg10();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}
const handleAvatarSuccess11: UploadProps['onSuccess'] = (response, uploadFile) => {
  add.img = response.data,
    add.supplierType = 11
  console.log(response);
  axios.post("http://localhost:5153/api/DeepProcessing/AddSupplier", add).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg11();

    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}

//显示
const GetproductsImg1 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params:{batch:localStorage.getItem("batch"),supplierType:1} }).then(res => {
    console.log(res.data);
    reportImgs.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      supplierType: 1
    }))
    console.log(reportImgs.value)
  })
}
const GetproductsImg2 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params: {batch:localStorage.getItem("batch"),supplierType:2} }).then(res => {
    console.log(res.data);
    animalImgs.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      supplierType: 2
    }))
    console.log(animalImgs.value)
  })
}
const GetproductsImg3 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params: {batch:localStorage.getItem("batch"),supplierType:3} }).then(res => {
    console.log(res.data);
    companyImgs.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      supplierType: 3
    }))
    console.log(companyImgs.value)
  })
}
const GetproductsImg4 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params: {batch:localStorage.getItem("batch"),supplierType:4} }).then(res => {
    console.log(res.data);
    slaughterImgs.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      supplierType: 4
    }))
    console.log(slaughterImgs.value)
  })
}
const GetproductsImg5 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params: {batch:localStorage.getItem("batch"),supplierType:5} }).then(res => {
    console.log(res.data);
    slaughterFirmImgs.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      supplierType: 5
    }))
    console.log(slaughterFirmImgs.value)
  })
}
const GetproductsImg6 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params: {batch:localStorage.getItem("batch"),supplierType:6} }).then(res => {
    console.log(res.data);
    foodSafeImgs.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      supplierType: 6
    }))
    console.log(foodSafeImgs.value)
  })
}
const GetproductsImg7 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params: {batch:localStorage.getItem("batch"),supplierType:7} }).then(res => {
    console.log(res.data);
    DeepEnterpriseImgs.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      supplierType: 7
    }))
    console.log(DeepEnterpriseImgs.value)
  })
}
const GetproductsImg8 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params: {batch:localStorage.getItem("batch"),supplierType:8} }).then(res => {
    console.log(res.data);
    SupplierImgs1.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      supplierType: 8
    }))
    console.log(SupplierImgs1.value)
  })
}
const GetproductsImg9 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params: {batch:localStorage.getItem("batch"),supplierType:9} }).then(res => {
    console.log(res.data);
    SupplierImgs2.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      supplierType: 9
    })) 
    console.log(SupplierImgs2.value)
  })
}
const GetproductsImg10 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params: {batch:localStorage.getItem("batch"),supplierType:10} }).then(res => {
    console.log(res.data);
    SupplierImgs3.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      supplierType: 10
    }))
    console.log(SupplierImgs3.value)
  })
}
const GetproductsImg11 = () => {
  axios.get("http://localhost:5153/api/DeepProcessing/GetSupplier", { params: {batch:localStorage.getItem("batch"),supplierType:11} }).then(res => {
    console.log(res.data);
    SupplierImgs4.value = (res.data.data || []).map((imgs: any) => ({
      name: imgs.img.split('/').pop(),
      url: imgs.img,
      batch: imgs.batch,
      SupplierType: 11
    }))
    console.log(SupplierImgs4.value)
  })
}


//删除
const handleRemove: UploadProps['onRemove'] = (uploadFile: any, uploadFiles) => {
  axios({
    url: 'http://localhost:5153/api/DeepProcessing/DelSupplier',
    method: 'post',
    params: { Id: uploadFile.id }
  }
  ).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetproductsImg1();
      GetproductsImg2();
      GetproductsImg3();
      GetproductsImg4();
      GetproductsImg5();
      GetproductsImg6();
      GetproductsImg7();
      GetproductsImg8();
      GetproductsImg9();
      GetproductsImg10();
    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
}

onMounted(() => {
  GetproductsImg1();
})
const handleExceed = () => {
  ElMessage.warning("最多上传9张图片")
}
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePreview = (file: any) => {
  dialogImageUrl.value = file.url || file.response?.url
  dialogVisible.value = true
}

</script>

<style scoped>
.main-layout {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: #f5f6fa;
}

.tabs-bar {
  background: #f5f6fa;
  padding: 0 24px;
  border-bottom: 1px solid #f0f0f0;
  min-height: 48px;
  display: flex;
  align-items: center;
}

.tab-item {
  background: #fff;
  border-radius: 6px 6px 0 0;
  padding: 10px 32px 10px 16px;
  font-size: 16px;
  font-weight: bold;
  margin-right: 8px;
  position: relative;
  cursor: pointer;
}

.tab-item.active {
  color: #2d8cf0;
  border-bottom: 2px solid #2d8cf0;
}

.tab-close {
  position: absolute;
  right: 8px;
  top: 10px;
  color: #bbb;
  font-size: 16px;
  cursor: pointer;
}

.content-area {
  flex: 1;
  display: flex;
  justify-content: center;
  background: #fff;
  padding: 0;
  overflow-y: auto;
}

.details-container {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  min-width: 900px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: 600px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  justify-content: flex-start;
}

.header-img-wrap {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 180px;
  height: 180px;
  margin-right: 40px;
}

.main-img {
  width: 160px;
  height: 160px;
  object-fit: cover;
  border-radius: 16px;
  border: 1px solid #eee;
}

.header-info {
  flex: 1;
  margin-left: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.title {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 12px;
}

.meta-row {
  color: #666;
  font-size: 16px;
  margin-bottom: 6px;
  display: flex;
  gap: 32px;
}

.header-btns {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-left: 40px;
  align-items: flex-end;
}

.section {
  margin-top: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
}

.img-list {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.img-item {
  position: relative;
  width: 120px;
  height: 120px;
  margin-bottom: 8px;
}

.img-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #eee;
}

.img-delete {
  position: absolute;
  top: -10px;
  right: -10px;
  background: #fff;
  border-radius: 50%;
  color: #f56c6c;
  font-size: 20px;
  cursor: pointer;
  border: 1px solid #eee;
  z-index: 2;
}

.upload-btn {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  cursor: pointer;
}

.tabs {
  margin-top: 24px;
}

.tab-section {
  background: #f9fafe;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 24px 24px 16px 24px;
  margin-bottom: 24px;
  border-left: 4px solid #2d8cf0;
}

.tab-title {
  font-size: 18px;
  font-weight: bold;
  color: #2d8cf0;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.img-list {
  gap: 20px;
}

.img-item {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.2s;
  border: 1px solid #e6e6e6;
}

.img-item:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 16px rgba(45, 140, 240, 0.12);
}

.img-item img {
  border-radius: 8px;
}

.img-label {
  background: linear-gradient(90deg, #2d8cf0 0%, #1890ff 100%);
  color: #fff;
  font-size: 14px;
  border-radius: 0 0 8px 8px;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 28px;
  line-height: 28px;
  width: 100%;
  text-align: center;
  opacity: 0.92;
}

.set-btn {
  margin-bottom: 0;
  margin-left: 8px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>